import router from './router';
import {getToken, getRouters, getUserMenusList} from "./utils/auth";
import {isMoblie} from './utils/public'
import store from './store'

/*
 * 判断是否cook里的token是否有效
 * 如果有效则继续跳转到访问页面
 * 无效则跳转至登录页面
 * */

router.beforeEach(function (to, from, next) {
  try {
    let jumpPath = to.path;
    let nextUrlList = ['/login', '/error'];//此处定义无需权限判断的访问路径
    if (nextUrlList.indexOf(jumpPath) < 0) {
      if (!getToken()) { //判断是否有访问令牌
        //在着可以判断做PC端或者是手机端
        next('/login');
      } else {
        if (!store.getters.routeFlag) {
          let routerArr = getRouters();
          if (!routerArr.length) {
            next({name: 'ErrorPage', params: {errorType: '您没有访问权限，请联系管理员'}});
            return;
          }
          router.addRoutes(routerArr);
          store.dispatch('user/setRouteFlag', true);
        }
        if (to.matched.length === 0 && jumpPath !== '/') {
          next('/');
          return;
        }
        if (jumpPath === '/') {
          let UserMenusList = getUserMenusList();//获取用户访问路径的List//如果访问根路径就直接跳转至菜单列表中的第一个地址
          let defaultUrl = UserMenusList[0];
          if (isMoblie()) defaultUrl = `/mobile${defaultUrl}`;
          next(defaultUrl);
        } else {
          next();
        }
      }
    } else {
      next();
    }
  } catch (e) {
    next('/error');
  }
});
